// 图片解析
document.getElementById('fileInput').addEventListener('change', function(e) {
    const file = e.target.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function(event) {
            const img = new Image();
            img.onload = function() {
                // 显示预览图
                const preview = document.getElementById('preview');
                preview.src = event.target.result;
                preview.style.display = 'block';

                // 创建 canvas
                const canvas = document.createElement('canvas');
                const context = canvas.getContext('2d');
                
                // 设置适当的大小
                const MAX_SIZE = 1024;
                let width = img.width;
                let height = img.height;
                
                // 如果图片太大，等比例缩小
                if (width > MAX_SIZE || height > MAX_SIZE) {
                    if (width > height) {
                        height = height * (MAX_SIZE / width);
                        width = MAX_SIZE;
                    } else {
                        width = width * (MAX_SIZE / height);
                        height = MAX_SIZE;
                    }
                }
                
                canvas.width = width;
                canvas.height = height;
                
                // 绘制图片
                context.drawImage(img, 0, 0, width, height);
                
                try {
                    // 获取图像数据
                    const imageData = context.getImageData(0, 0, width, height);
                    
                    // 尝试解析
                    const code = jsQR(imageData.data, width, height, {
                        inversionAttempts: "dontInvert"
                    });
                    
                    if (code) {
                        document.getElementById('imageResult').textContent = code.data;
                        showToast('二维码解析成功');
                    } else {
                        // 如果第一次解析失败，尝试反转颜色再解析
                        const code2 = jsQR(imageData.data, width, height, {
                            inversionAttempts: "onlyInvert"
                        });
                        
                        if (code2) {
                            document.getElementById('imageResult').textContent = code2.data;
                            showToast('二维码解析成功');
                        } else {
                            document.getElementById('imageResult').textContent = '未检测到二维码，请确保：\n1. 图片清晰\n2. 二维码完整\n3. 光线充足';
                            showToast('未检测到二维码');
                        }
                    }
                } catch (error) {
                    console.error('解析错误：', error);
                    document.getElementById('imageResult').textContent = '解析失败，请尝试其他图片';
                    showToast('解析失败');
                }
            };
            img.onerror = function() {
                showToast('图片加载失败');
                document.getElementById('imageResult').textContent = '图片加载失败，请检查图片格式';
            };
            img.src = event.target.result;
        };
        reader.onerror = function() {
            showToast('文件读取失败');
            document.getElementById('imageResult').textContent = '文件读取失败，请重试';
        };
        reader.readAsDataURL(file);
    }
});

// 摄像头扫描
let videoStream;
const video = document.getElementById('video');
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');

async function startCamera() {
    try {
        videoStream = await navigator.mediaDevices.getUserMedia({ 
            video: { facingMode: "environment" } 
        });
        video.srcObject = videoStream;
        video.style.display = 'block';
        video.play();
        requestAnimationFrame(scanQRCode);
    } catch (err) {
        showToast('无法访问摄像头：' + err.message);
    }
}

function stopCamera() {
    if (videoStream) {
        videoStream.getTracks().forEach(track => track.stop());
        video.style.display = 'none';
        document.getElementById('cameraResult').textContent = '';
    }
}

function scanQRCode() {
    if (video.readyState === video.HAVE_ENOUGH_DATA) {
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        context.drawImage(video, 0, 0);
        const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
        
        try {
            const code = jsQR(imageData.data, imageData.width, imageData.height, {
                inversionAttempts: "dontInvert"
            });
            
            if (code) {
                document.getElementById('cameraResult').textContent = code.data;
                showToast('二维码解析成功');
                stopCamera();
                return;
            }
        } catch (error) {
            console.error('扫描出错：', error);
        }
    }
    if (videoStream) {
        requestAnimationFrame(scanQRCode);
    }
}

function showToast(message) {
    const toast = document.getElementById('toast');
    toast.classList.remove('show');
    void toast.offsetWidth;
    toast.textContent = message;
    toast.classList.add('show');
    setTimeout(() => {
        toast.classList.remove('show');
    }, 2000);
}

// 页面卸载时清理资源
window.addEventListener('beforeunload', () => {
    stopCamera();
}); 